angular.module("application")
.controller('timelineCtrl', function($scope, $q, $routeParams, $location, $timeout, mapTimelineProcess, renderProcess, BASE_URL) 
{	
	if($routeParams.region != 'vn' && $routeParams.region != 'wo') {
		$location.path('/');
	}
	$scope.events = [];
	$scope.timeline = [];
	$scope.region = $routeParams.region; // Choose VN or WO Timeline
	$scope.curCentury = 0;
	$scope.curYear = 0;

	var swFlag = 0;
	var bigMap = null;
	var elementsMap = null;

	$scope.option = {frYear: null, toYear: null};
	$scope.filterNation = null;
	// $scope.regexNumber = ;

	// $scope.$parent.loadingView = true; // Show loading spinner

	$scope.listNations = [];
	mapTimelineProcess.getListNation().then(function(promise) {
		console.log(promise.data);
		angular.forEach(promise.data, function(data) {
			$scope.listNations.push(data);
		})
	});
	console.log($scope.listNations);

	var getDataPromise = mapTimelineProcess.getData($scope.region);
	getDataPromise.then(function() {
		deferred = $q.defer();
		setTimeout(function() {
			$scope.$apply(function() {
				$scope.$parent.loadingView = false;
			});
			deferred.resolve();
		},500);
		return deferred.promise;
	})
	.then(function() 
	{ 
		setTimeout(function() { // Avoid issue with ngAnimate Library

			$("#main-content").css({ // Set map Container Size
				'width': viewport().width - 100 + 'px',
				'height': viewport().height - 100 + 'px'
			});
			// Create map
			bigMap = mapTimelineProcess.initialMap($scope.region);

			// Congigure Slider
			mapTimelineProcess.slidersInit();
		
			// Get event Data
			getDataPromise.then(function(result) {
				$scope.events = result['events']['data'];
				data = result['events']['data'];

				// resize List Event - style
				renderProcess.setListHeight();

				times = result['times']['data'];
				$scope.timeline = mapTimelineProcess.makeTimeline(times);
				// console.log($scope.timeline);

				for(node in $scope.timeline) {
					$('#centuries-frame .slidee').append('<li class="century" century="'+ $scope.timeline[node]['val'] +'">' + $scope.timeline[node]['str'] + '</li>');
					$('#years-frame .slidee').append('<li class="head '+ node + '" century="' + $scope.timeline[node]['val'] + '"></li>');

					for(year in $scope.timeline[node]['years']) {
						y = $scope.timeline[node]['years'][year];
						if(y < 0) str = 'Năm ' + Math.abs(y) + ' TCN';
						else str = 'Năm ' + y;
						$('#years-frame .slidee').append('<li class="year '+ node + '" century="'+ $scope.timeline[node]['val'] + '" year="' + y + '">'+ str +'</li>');
					}
				}

				$('#centuries-frame').sly('reload');
				$('#years-frame').sly('reload');
			});

			// ============================================================================================
			// trigger click on Timeline===================================================================
			$('.timeline').on('mousedown touchstart', function() {
				swFlag = 1; console.log(swFlag);
			});
			$('#years-frame').sly('on','active', function() {

				// Cancel all http in previous time
				mapTimelineProcess.abortMapHttp();

				if(swFlag == 1) {
					var classes = $('#years-frame .slidee .active').attr('class');
					classes= classes.split(' ');
					var century = classes[1];
					swFlag = 0;			
					$('#centuries-frame').sly('activate', century);
				}

				// get Year and Century
				var item = $('#years-frame .slidee li').get(this.rel['activeItem']);
				setTimeout(function () {
					$scope.$apply(function () {
						// $scope.message = "Timeout called!";
						$scope.curCentury = $(item).attr('century');
						$scope.curYear = $(item).attr('year');					
					});
				}, 10);
				
				// Clear range Time
					$scope.option = {frYear: null, toYear: null};

			});
			$('#centuries-frame').sly('on','active', function() {
				if(swFlag == 1) {
					// setTimeout(function() {
						var head = this.rel['activeItem'];
						item = $('#years-frame .slidee li.head').get(head);
						index = $('#years-frame li').index(item);
						$('#years-frame').sly('activate', index);
						swFlag = 0;
					// },50);					
				}
			}); // end trigger funcitons

		}, 10);
	});

	// watch $scope variables changed
	$scope.$watchCollection('[curCentury, curYear]', function() {
		// Style color timeline and refresh map by events
		styleTime($scope.curCentury);		
		clearMap(elementsMap);
		$timeout(function() {
			timelinePc = mapTimelineProcess.eventsToMap($scope.events, $scope.curCentury, $scope.curYear, bigMap, -1)
		}, 500);

		timelinePc.then(function(dt) {
			elementsMap = dt;
			// alert('done');
		})
	});

	$('#main-timeline').mousedown(function(e) { 
		e.preventDefault(); 
	});


	// =======================================================================================================
	// =======================================================================================================
	$scope.viewMap = function(eventId) {
		mapTimelineProcess.changeView(eventId);
	}

	$scope.setRangeTime = function() {
		toY = $scope.option.toYear;
		frY = $scope.option.frYear;
		if(frY > toY) {
			$('#time-form-alert').modal('show');
			return;
		}
		clearMap(elementsMap);
		if($scope.filterNation)
			elementsMap = mapTimelineProcess.eventsToMap($scope.events, frY, toY, bigMap, $scope.filterNation._id);
		else elementsMap = mapTimelineProcess.eventsToMap($scope.events, frY, toY, bigMap, 0); 
		$("#time-popup").modal("hide");
	}
});

function styleTime(century) {
	$('#years-frame .slidee li').removeClass("in-cent");
	$('#years-frame .slidee li').each(function() {
		if($(this).attr('century') == century) {
			$(this).addClass("in-cent");
		}
	})
}


function clearMap(elements) {
	if(elements) {
		for(i in elements) {
			elements[i].setMap(null);
		}
	}
}

